import { EnumGender, EnumMemberIdentity, HomeMemberEditRequest } from "@/apis/endpoint/model";
import { postMyEdituserinfo } from "@/apis/endpoint/my";
import { fileUpload } from "@/apis/upload";
import GpContainer from "@/components/GpContainer";
import GpFontIcon from "@/components/GpFontIcon";
import { GpTouchableView } from "@/components/GpTouchableView";
import { pageMapper } from "@/constants/pageMap";
import { dateFormat, dateUtil } from "@/utils/date";
import { isSetValue, privatifyMobile } from "@/utils/helper";
import { navigate } from "@/utils/navigation";
import { DatetimePicker, Popup } from "@taroify/core";
import { Button, Image, Text, View } from "@tarojs/components";
import Taro from "@tarojs/taro";
import clsx from "clsx";
import { Fragment, useEffect, useMemo, useRef, useState } from "react";
import { useImmer } from "use-immer";
import { GpSwitch } from "../components/GpSwitch";
import styles from "./index.module.css";
import { validateScheme } from "@/utils/app";
import { genderOptions, identityOptions } from "../enum-options";
import { useAuthStore } from "@/store";

interface State {
  avatar?: string
  name?: string
  gender?: EnumGender
  birth?: Date
  identity?: EnumMemberIdentity
  worktime?: Date
  mobile?: string
  mobileCode?: string
  weChat?: string
  email?: string
}
export default function Index() {
  const sexOptions = genderOptions.slice(0, 2)
  const [loading, setLoading] = useState(false)
  const [openBirth, setOpenBirth] = useState(false)
  const [openWorktime, setOpenWorktime] = useState(false)
  const [state, setState] = useImmer(getInitialState())
  const fetchMemberProfile = useAuthStore(state => state.fetchMemberProfile)
  const worktimeDesc = useMemo(() => {
    if (!state.worktime) return ""
    const diff = dateUtil().diff(state.worktime, "y")
    return `（${diff}年经验）`
  }, [state.worktime])
  const timeRange = useRef({
    min: new Date(1980, 0, 1),
    max: new Date()
  })
  useEffect(() => {
    fetchMemberProfile()
    .then(userInfo => {
      setState(draft => {
        if (isSetValue(userInfo.gender)) {
          draft.gender = userInfo.gender === EnumGender.女 ? userInfo.gender : EnumGender.男
        }
        if (userInfo.birthday) {
          draft.birth = dateUtil(userInfo.birthday).toDate()
        }
        if (userInfo.workDate) {
          draft.worktime = dateUtil(userInfo.workDate).toDate()
        }
        ;(["avatar","name", "identity", "mobile", "weChat", "email"] as const).forEach(field => {
          if (isSetValue(userInfo[field])) {
            // @ts-ignore
            draft[field] = userInfo[field]
          }
        })
      })
    })
  }, [])
  function getInitialState(): State {
    return {
      avatar: __DEF_AVATAR__,
      gender: sexOptions[0].value,
      identity: identityOptions[0].value
    }
  }
  async function handleClickAvatar() {
    const { tapIndex } = await Taro.showActionSheet({
      itemList: ['拍照', '从相册中选择'],
      itemColor: "#313337"
    })
    const { tempFiles } = await Taro.chooseMedia({
      count: 1,
      mediaType: ['image'],
      sourceType: [tapIndex === 1 ? 'album' : 'camera']
    })
    const { fullName } = await fileUpload(tempFiles[0].tempFilePath)
    setState(draft => {draft.avatar = fullName})
  }
  function handleEditName() {
    navigate(
      pageMapper.fieldEdit.simple,
      null,
      "navigateTo",
      {
        events: {
          receiveField: function(name: string) {
            setState(state => {state.name = name})
          }
        },
        success(res) {
          res.eventChannel.emit("getField", {
            navigationbarTitleText: "姓名",
            placeholder: "请输入真实姓名",
            content: state.name,
            maxContent: 10,
            showTip: true,
            tip: "每月可修改3次，本月您还可以修改3次"
          } as FieldEditStateSimple)
        },
      },
    )
  }
  function handleEditMobile() {
    navigate(
      pageMapper.me.mobile,
      null,
      "navigateTo",
      {
        events: {
          acceptMobile: function({mobile,mobileCode}: {mobile: string;mobileCode: string;}) {
            setState(state => {
              state.mobile = mobile
              state.mobileCode = mobileCode
            })
          }
        }
      }
    )
  }
  function handleEditWechat() {
    navigate(
      pageMapper.me.wechat,
      state.weChat ? {wechat: encodeURIComponent(state.weChat)} : null,
      "navigateTo",
      {
        events: {
          acceptWechat: function({wechat}: {wechat: string}) {
            setState(state => {state.weChat = wechat})
          }
        }
      }
    )
  }
  function handleEditEmail() {
    navigate(
      pageMapper.fieldEdit.simple,
      null,
      "navigateTo",
      {
        events: {
          receiveField: function(email: string) {
            setState(state => {state.email = email})
          }
        },
        success(res) {
          res.eventChannel.emit("getField", {
            navigationbarTitleText: "邮箱",
            placeholder: "请输入邮箱",
            content: state.email,
          } as FieldEditStateSimple)
        },
      },
    )
  }
  async function handleSave() {
    const params = {} as HomeMemberEditRequest
    const isValid = validateScheme(state, params, {
      name: "name",
      mobile: "mobile",
      identity: "identity",
      birth: "birthday",
      worktime: "workDate"
    }, {
      name: {
        field: "name",
        dataField: "name",
        message: "请填写姓名",
        getValue(value) {
          return value!
        },
      },
      mobile: {
        field: "mobile",
        dataField: "mobile",
        message: "请设置手机号",
        getValue(value) {
          return value!
        },
      },
      identity: {
        field: "identity",
        dataField: "identity",
        message: "请设置你的身份",
        getValue(value) {
          return value!
        },
      },
      birth: {
        field: "birth",
        dataField: "birthday",
        message: "请设置你的出生年月",
        getValue(value) {
          return dateFormat(value, "long")
        },
      },
      worktime: {
        field: "worktime",
        dataField: "workDate",
        message: "请设置你参加工作的时间",
        getValue(value) {
          return dateFormat(value, "long")
        },
      }
    })
    if (!isValid) return;

    ;(["avatar", "mobileCode", "gender", "weChat", "email"] as const).forEach(field => {
      // @ts-ignore
      if (isSetValue(state[field])) params[field] = state[field]
    });

    setLoading(true)
    await postMyEdituserinfo(params).send({showLoading: false})
    await fetchMemberProfile(false)
    setLoading(false)
    Taro.showToast({
      title: "编辑成功",
      icon: "success"
    })
    navigate()
  }
  function renderHeader() {
    return (
      <View className={clsx("h-[214px] flex flex-row px-[44px] pt-[40px] pb-[46px]", styles.header)}>
        <Image src={state.avatar!} className="object-cover size-[128px] mr-[28px] rounded-[50%]" onClick={handleClickAvatar} />
        <View className="flex flex-col justify-end">
          <Text className="text-[36px] leading-[36px] font-medium text-primary">头像</Text>
          <Text className="text-[24px] leading-[24px] font-normal text-[#ACAEB2] py-[16px]">真实头像更容易提升求职成功率</Text>
        </View>
      </View>
    )
  }
  function renderList() {
    return (
      <View className="px-[16px] box-border">
        <GpTouchableView className={styles["list-item"]} onClick={handleEditName}>
          <Text className="text-third text-[28px] flex-1">姓名</Text>
          <Text className={clsx("text-[32px] flex-none", state.name ? "text-primary font-bold" : "text-placeholder")}>
            { state.name || "请输入真实姓名"}
          </Text>
          <GpFontIcon name="icon-a-jiantou_youxiao" size={28} color="#ACAEB2" className="ml-[16px] flex-none" />
        </GpTouchableView>
        <View className={styles["list-item"]}>
          <Text className="text-third text-[28px] flex-1">性别</Text>
          <GpSwitch<number>
            value={state.gender!}
            options={sexOptions}
            className="w-[264px]"
            onChange={value => setState(draft => {draft.gender = value})}
            renderItem={(option, active) => (
              <Fragment>
                <Text className={clsx(active ? 'text-primary font-bold' : 'text-third font-normal', 'text-[32px]')}>{option.label}</Text>
                <GpFontIcon name={option.value === 1 ? "icon-nanxing" : "icon-nvxing"} size={28} className={clsx(active ? option.value === 1 ? 'text-theme' : 'text-[#EF5476]' : 'text-placeholder', 'ml-[12px]')} />
              </Fragment>
            )}
          />
        </View>
        <GpTouchableView className={styles["list-item"]} onClick={() => setOpenBirth(true)}>
          <Text className="text-third text-[28px] flex-1">出生年月</Text>
          <Text className={clsx("text-[32px] flex-none", state.birth ? "text-primary font-bold" : "text-placeholder")}>
            {state.birth ? dateFormat(state.birth, "YYYY.MM.DD") : "请选择"}
          </Text>
          <GpFontIcon name="icon-a-jiantou_youxiao" size={28} color="#ACAEB2" className="ml-[16px] flex-none" />
        </GpTouchableView>
        <View className={styles["list-item"]}>
          <Text className="text-third text-[28px] flex-1">我的身份</Text>
          <GpSwitch<number>
            value={state.identity!}
            options={identityOptions}
            className="w-[312px]"
            onChange={value => setState(draft => {draft.identity = value})}
            renderItem={(option, active) => (
                <Text className={clsx(active ? 'text-primary font-bold' : 'text-third font-normal', 'text-[32px]')}>{option.label}</Text>
            )}
          />
        </View>
        <GpTouchableView className={styles["list-item"]} onClick={() => setOpenWorktime(true)}>
          <Text className="text-third text-[28px] flex-1">参加工作时间</Text>
          <Text className={clsx("text-[32px] flex-none", state.worktime ? "text-primary font-bold" : "text-placeholder")}>
            {state.worktime ? `${dateFormat(state.worktime, "YYYY.MM")} ${worktimeDesc}` : "请选择"}
          </Text>
          <GpFontIcon name="icon-a-jiantou_youxiao" size={28} color="#ACAEB2" className="ml-[16px] flex-none" />
        </GpTouchableView>
        <GpTouchableView className={styles["list-item"]} onClick={handleEditMobile}>
          <View className="flex-1 flex flex-col">
            <Text className="text-third text-[28px]">手机号码</Text>
            <Text className="text-placeholder text-[24px] mt-[8px]">仅用于与HR交换手机</Text>
          </View>
          <Text className={clsx("text-[32px] flex-none", state.mobile ? "text-primary font-bold" : "text-placeholder")}>
            {state.mobile ? privatifyMobile(state.mobile) : '未设置'}
          </Text>
          <GpFontIcon name="icon-a-jiantou_youxiao" size={28} color="#ACAEB2" className="ml-[16px] flex-none" />
        </GpTouchableView>
        <GpTouchableView className={styles["list-item"]} onClick={handleEditWechat}>
          <View className="flex-1 flex flex-col">
            <Text className="text-third text-[28px]">微信号</Text>
            <Text className="text-placeholder text-[24px] mt-[8px]">仅用于与HR交换微信</Text>
          </View>
          <Text className={clsx("text-[32px] flex-none", state.weChat ? "text-primary font-bold" : "text-placeholder")}>
            {state.weChat || "未设置"}
          </Text>
          <GpFontIcon name="icon-a-jiantou_youxiao" size={28} color="#ACAEB2" className="ml-[16px] flex-none" />
        </GpTouchableView>
        <GpTouchableView className={styles["list-item"]} onClick={handleEditEmail}>
          <Text className="text-third text-[28px] flex-1">邮箱</Text>
          <Text className={clsx("text-[32px] flex-none", state.email ? "text-primary font-bold" : "text-placeholder")}>
            {state.email || "请输入邮箱(选填)"}
          </Text>
          <GpFontIcon name="icon-a-jiantou_youxiao" size={28} color="#ACAEB2" className="ml-[16px] flex-none" />
        </GpTouchableView>
      </View>
    )
  }
  function renderAction() {
    return (
      <GpTouchableView className="mt-[104px] px-[32px] box-border">
        <Button className="text-center bg-theme h-[80px] leading-[80px] box-border rounded-[64px]" loading={loading} onClick={handleSave}>
          <Text className="text-white text-[32px]">保存</Text>
        </Button>
      </GpTouchableView>
    )
  }
  function renderActionPannels() {
    return <View>
      {renderBirth()}
      {renderWorktime()}
    </View>
  }
  function renderBirth() {
    return <Popup open={openBirth} rounded placement="bottom" onClose={setOpenBirth}>
        <Popup.Backdrop closeable={false} />
        <DatetimePicker
          type="date"
          min={timeRange.current.min}
          max={timeRange.current.max}
          value={state.birth}
          onConfirm={value => {
            setOpenBirth(false)
            setState(draft => {draft.birth = value})
          }}
          onCancel={() => setOpenBirth(false)}
        >
          <DatetimePicker.Toolbar>
            <DatetimePicker.Button type="cancel">取消</DatetimePicker.Button>
            <DatetimePicker.Title>出生年月</DatetimePicker.Title>
            <DatetimePicker.Button type="confirm">确认</DatetimePicker.Button>
          </DatetimePicker.Toolbar>
        </DatetimePicker>
    </Popup>
  }
  function renderWorktime() {
    return <Popup open={openWorktime} rounded placement="bottom" onClose={setOpenWorktime}>
        <Popup.Backdrop closeable={false} />
        <DatetimePicker
          type="date"
          min={timeRange.current.min}
          max={timeRange.current.max}
          value={state.worktime}
          onConfirm={value => {
            setOpenWorktime(false)
            setState(draft => {draft.worktime = value})
          }}
          onCancel={() => setOpenWorktime(false)}
        >
          <DatetimePicker.Toolbar>
            <DatetimePicker.Button type="cancel">取消</DatetimePicker.Button>
            <DatetimePicker.Title>参加工作时间</DatetimePicker.Title>
            <DatetimePicker.Button type="confirm">确认</DatetimePicker.Button>
          </DatetimePicker.Toolbar>
        </DatetimePicker>
    </Popup>
  }
  return (
    <GpContainer className="bg-[#F4F6FC] pb-[32px]">
      {renderHeader()}
      {renderList()}
      {renderAction()}
      {renderActionPannels()}
    </GpContainer>
  )
}
